import type { FormProps } from 'antd'
import { Button, Form, InputNumber, message, Spin, Upload } from 'antd'
import { useEffect, useState } from 'react'
import http from '@/utils/request'
import { PlusOutlined } from '@ant-design/icons'

interface configType {
  id: string
  personalBackgroundImage: any
  recyclingTime: number
  successMonth: number
}
// @ts-ignore
const baseURL = import.meta.env.DEV ? import.meta.env.VITE_BASE_URL : window.location.origin

let pageConfig: Partial<configType> = {}
const GlobalConfig:React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true)
  const getCOnfig = () => {
    setLoading(true)
    http.get('/disp/biz/globalCfg/getDefault').then(res => {
      pageConfig = res.data
      form.setFieldsValue({
        recyclingTime: pageConfig.recyclingTime,
        successMonth: pageConfig.successMonth,
        personalBackgroundImage: pageConfig.personalBackgroundImage ? JSON.parse(pageConfig.personalBackgroundImage) : null
      })
    }).catch(err => {
      message.error(err.msg || '获取配置失败')
    }).finally(() => {
      setLoading(false)
    })
  }
  useEffect(() => {
    getCOnfig()
  }, [])

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }

  const onFinish: FormProps<configType>['onFinish'] = (values) => {
    const personalBackgroundImage = values.personalBackgroundImage.map((item: { uid: any; type: any; response: { data: any }; url: any; size: any; status: any; relativePath: any }) => {
      const relativePath = item.response?.data || item.relativePath
      return {
        uid: item.uid,
        type: item.type,
        url: `${baseURL}${relativePath}`,
        size: item.size,
        status: item.status,
        relativePath
      }
    })
    setLoading(true)
    http.post('/disp/biz/globalCfg/save', {
      ...values,
      id: pageConfig.id,
      personalBackgroundImage: JSON.stringify(personalBackgroundImage)
    }).then(() => {
      message.success('保存成功')
    }).catch(err => {
      message.error(err.msg || '保存失败')
    }).finally(() => {
      setLoading(false)
    })
  }
  const onFinishFailed: FormProps<configType>['onFinishFailed'] = (errorInfo) => {
    console.log(errorInfo)
  }

  const [form] = Form.useForm()
  return (
    <Spin spinning={loading}>
      <div className="page">
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          style={{ maxWidth: 800 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item label="订单显示月份" name="successMonth">
            <InputNumber style={{ width:'100%' }} />
          </Form.Item>
          <Form.Item label="回收时间"
            name="recyclingTime"
            extra="系统计算未处理订单，默认设置为未完成的时间：18-23，整数。若设置为18，则每日18时会将当天所有未处理订单回收"
            rules={[
              {
                validator: (_, value) => {
                  if (value === null || value === undefined || value === '') {
                    return Promise.reject(new Error('请设置回收时间'))
                  }
                  if (!Number.isInteger(value)) {
                    return Promise.reject(new Error('回收时间必须是整数'))
                  }
                  if (value < 18 || value > 23) {
                    return Promise.reject(new Error('回收时间必须在18到23之间'))
                  }
                  return Promise.resolve()
                }
              }]}>
            <InputNumber max={23} min={18} style={{ width:'100%' }} />
          </Form.Item>
          <Form.Item
            label="个人页壁纸"
            name="personalBackgroundImage"
            valuePropName="fileList"
            getValueFromEvent={normFile}
            rules={[{ required: false, message: '请上传壁纸图片' }]}>
            <Upload
              action={`${baseURL}/disp/common/file/uploadImage`}
              listType="picture-card">
              <button
                style={{ color: 'inherit', cursor: 'inherit', border: 0, background: 'none' }}
                type="button"
              >
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </button>
            </Upload>
          </Form.Item>
          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">保存</Button>
          </Form.Item>
        </Form>
      </div>
    </Spin>)
}

export default GlobalConfig